<template>
  <div>
    <el-dialog :title="`${$t('basic.stage')}：PH_OTM`" :visible.sync="isShowOTM" :close-on-click-modal="false"
      :before-close="handleClose" :width="screenWidth > 1310 ? '55%' : '70%'" v-dialogDrag>
      <el-form :model="formData" label-width="70px" ref="ruleForm" size="mini" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="24" class="gz-form-row">
          
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.isAuto">{{$t('common.auto_start')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="10" :md="8" :lg="6" :xl="6">
            <el-form-item :label="$t('common.start_delay')" label-width="70px" class="inputPadding">
              <el-input type="number" v-model="formData.delayTime">
                <template slot="append">min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.mode">{{$t('common.operation_signature')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :md="5" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.checks">{{$t('common.review_confirmation')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="12" :sm="12" :md="8" :lg="8" :xl="8">
                        <el-form-item :label="$t('basic.stage_name')" prop="phaseDesc">
                            <el-input disabled v-model="formData.phaseDesc" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col> -->
          <!-- <el-col :xs="12" :sm="6" :md="2" :lg="2" :xl="2">
                        <el-form-item :label="$t('common.enable')">
                            <el-checkbox v-model="formData.isAuto" @change="changeIsActive"></el-checkbox>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="5" :lg="6" :xl="4">
                        <el-form-item label="数字签名" label-width="115px">
                            <el-checkbox v-model="formData.signitature" @change="changeIsActive"></el-checkbox>
                        </el-form-item>
                    </el-col> -->
        </el-row>
        <el-row :gutter="24" class="gz-form-row">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="itemId">
            <el-form-item :label="$t('basic.reason_group')">
              <el-select v-model="formData.reasGrpId" remote filterable :remote-method="remoteMethodCause" placeholder="" clearable
                @clear="clearCause">
                <el-option v-for="(item,index) in causeList" :key="index" :label="item.reasGrpDesc" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="itemId">
            <el-form-item :label="$t('basic.material')" prop="itemId">
              <el-select v-model="formData.itemId" remote filterable :remote-method="remoteMethodMaterial" placeholder=""
                v-el-select-loadmore="loadMoreMaterialFun" clearable @clear="clearMaterial" @change="changeItemId">
                <el-option v-for="(item,index) in materialList" :key="index" :label="item.fid" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('recipe.the_number')" prop="qty">
              <el-input type="number" v-enterNumber2 v-model="formData.qty" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('basic.company')">
              <el-input v-model="formData.uom" disabled placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('common.upper_limit')" prop="hi">
              <el-input type="number" v-enterNumber2 v-model="formData.hi" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('common.lower_limit')" prop="lo">
              <el-input type="number" v-enterNumber2 v-model="formData.lo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="24">
                    <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                        <el-form-item :label="$t('common.upper_limit')" prop="hi">
                            <el-input type="number" v-enterNumber2 v-model="formData.hi" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                        <el-form-item :label="$t('common.lower_limit')" prop="lo">
                            <el-input type="number" v-enterNumber2 v-model="formData.lo" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row> -->
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label-width="0">
              <!-- <el-checkbox v-model="formData.confirm" @change="changeIsActive"> -->
              <p style="font-weight: bold">{{$t('recipe.phase_info')}}</p>
              <!-- </el-checkbox> -->
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('common.operating_instructions')">
              <el-input rows="3" type="textarea" v-model="formData.guideInfo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('basic.remarks')">
              <el-input rows="3" type="textarea" v-model="formData.flastModifyComment" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :disabled="isreadOnly" :loading="loading"
          @click="handleConfirm('ruleForm')">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { configure } from "@/api/configure"
import { formula } from "@/api/formula"
export default {
  props: {
    isShowOTM: Boolean,
    tdIndex: Number,
    stepObj: Object,
    isreadOnly: Boolean
  },
  data () {
    let HiFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(this.formData.qty) > parseFloat(value)) {
          callback(new Error('物料上限不能小于物料数量'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    let LoFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(value) > parseFloat(this.formData.qty)) {
          callback(new Error('物料下限不能大于物料数量'));
        } else if (this.formData.hi) {
          if (parseFloat(value) > parseFloat(this.formData.hi)) {
            callback(new Error('物料下限不能大于物料上限'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      screenWidth: document.body.clientWidth,
      formData: {
        seqNo: "",
        delayTime: "",
        mode: "",
        checks: "",
        stepNo: "",
        stepDesc: "",
        isActive: false,
        itemId: "",
        qty: "",
        uom: "",
        phaseDesc: "物料产出",
        confirm: "",
        flastModifyComment: "",
        guideInfo: "",
        isAuto: false,
        hi: "",
        lo: "",
        reasGrpId: "",
        stepSort: 0,
      },
      rules: {
        itemId: [{ required: true, message: '请选择物料名称', trigger: 'change' }],
        qty: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        hi: [{ validator: HiFn, trigger: 'blur' }],
        lo: [{ validator: LoFn, trigger: 'blur' }]
      },
      loading: false,
      materialList: [],
      pager: {
        pageNum: 1,
        pageSize: 10,
      },
      pagerGroup: {
        pageNum: 1,
        pageSize: 50,
        keyword: ""
      },
      keyword: "",
      stepLoading: false,
      list: [],
      phaseId: "",
      fid: "",
      causeList: []
    }
  },
  watch: {
    screenWidth (val) {
      this.screenWidth = Number(val)
    },
    isShowOTM (val) {
      if (val) {
        this.formData.confirm = this.stepObj.confirm == 1 ? true : false
        this.formData.flastModifyComment = this.stepObj.flastModifyComment
        this.formData.guideInfo = this.stepObj.guideInfo
        this.formData.isActive = this.stepObj.isActive == 1 ? true : false
        this.formData.isAuto = this.stepObj.isAuto == 1 ? true : false
        this.formData.signitature = this.stepObj.signitature == 1 ? true : false
        this.formData.reasGrpId = this.stepObj.reasGrpId
        this.formData.stepNo = this.tdIndex
        this.formData.mode = this.stepObj.mode == 1 ? true : false
        this.formData.checks = this.stepObj.checks == 1 ? true : false
        this.formData.delayTime = this.stepObj.delayTime

        this.phaseId = this.stepObj.fid || this.stepObj.fId
        this.formData.seqNo = this.tdIndex
        this.formData.phaseDesc = this.stepObj.texts
        if (this.stepObj.fid || this.stepObj.fId) {
          this.phaseOtmList()
        }
        this.formData.stepSort = this.stepObj.stepSort ?? 0
      } else {
        for (let key in this.formData) {
          this.formData[key] = ""
        }
        this.phaseId = ""
      }
    }
  },
  mounted () {
    const that = this
    window.addEventListener('resize', function () {
      that.screenWidth = document.body.offsetWidth;
    })
  },
  created () {
    this.getReasGroupList()
    this.getItemList()
  },
  methods: {
    getItemList () {
      const param = {
        className: this.keyword,
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        itemClassVo: {
          produced: 1
        }
      }
      configure.getItemList(param).then(res => {
        if (res.code == 200) {
          this.materialList = [...this.materialList, ...res.data.rows]
        }
      })
    },
    phaseOtmList () {
      const param = {
        phaseId: this.stepObj.fid
      }
      formula.phaseOtmList(param).then(res => {
        if (res.code == 200) {
          if (res.data.rows.length > 0) {
            this.list = res.data.rows
            this.formData.itemId = res.data.rows[0].itemId
            this.formData.qty = res.data.rows[0].qty
            this.formData.uom = res.data.rows[0].uom
            this.fid = res.data.rows[0].fid
            this.formData.hi = res.data.rows[0].hi
            this.formData.lo = res.data.rows[0].lo
          } else {
            this.fid = ''
            this.list = []
          }

        } else {
          this.fid = ''
          this.list = []
        }
      }).catch(e => {
        this.fid = ''
        this.list = []
      })
    },
    handleClose () {
      this.$refs["ruleForm"].resetFields();
      this.$emit("closePH", "OTM")
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = {
            phaseDesc: this.formData.phaseDesc,
            isAuto: this.formData.isAuto == false ? 0 : 1,
            isActive: this.formData.isActive == false ? 0 : 1,
            checks: this.formData.checks == false ? 0 : 1,
            delayTime: this.formData.delayTime,
            operationId: this.stepObj.operationId,
            type: this.stepObj.type,
            confirm: this.formData.confirm == false ? 0 : 1,
            flastModifyComment: this.formData.flastModifyComment,
            guideInfo: this.formData.guideInfo,
            mode: this.formData.mode == false ? 0 : 1,
            seqNo: this.stepObj.seqNo,
            stepNo: this.stepObj.stepNo,
            phaseCode: this.stepObj.phaseCode,
            signitature: this.formData.signitature == false ? 0 : 1,
            serialNo: this.stepObj.serialNo,
            reasGrpId: this.formData.reasGrpId,
            stepSort: this.formData.stepSort,
          }
          if (this.phaseId) {
            param.fid = this.phaseId
          }
          this.loading = true
          formula.phaseAdd(param).then(res => {
            this.loading = false
            if (res.code == 200) {
              this.phaseOtmAdd()
            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })
    },
    phaseOtmAdd () {
      const params = {
        itemId: this.formData.itemId,
        qty: this.formData.qty,
        uom: this.formData.uom,
        phaseId: this.stepObj.fid,
        fid: this.fid,
        lo: this.formData.lo,
        hi: this.formData.hi,
        seq: 1
      }
      formula.phaseOtmAdd(params, this.list).then(res => {
        this.loading = false
        if (res.code == 200) {
          let obj = {
            mode: this.stepObj.mode,
            isAuto: this.formData.isAuto == false ? 0 : 1,
            isActive: this.formData.isActive == false ? 0 : 1,
            operationId: this.stepObj.operationId,
            seqNo: this.stepObj.seqNo,
            serialNo: this.stepObj.serialNo,
            text: this.stepObj.phaseDesc
          }
          this.$emit("uptionData", obj)
          this.$emit("closePH", "OTM")
        } else {
          this.$message.error(res.msg);
        }
      }).catch(e => {
        this.loading = false
      })
    },
    remoteMethodMaterial (keyword) {
      this.keyword = keyword.trim();
      this.pager.pageNum = 1
      setTimeout(() => {
        this.materialList = []
        this.getItemList()
      }, 200)
    },
    loadMoreMaterialFun () {
      this.pager.pageNum++
      this.getItemList()
    },
    clearMaterial () {
      this.keyword = ""
      this.pager.pageNum = 1
      this.materialList = []
      this.getItemList()
    },
    changeItemId (val) {
      this.formData.uom = this.materialList.find(item => item.fid == val).uomId
    },
    changeIsActive (val) {
      this.$forceUpdate()
    },
    changeCheck (val) {
      this.$forceUpdate()
    },
    remoteMethodCause (keyword) {
      this.pagerGroup.keyword = keyword.trim();
      this.pagerGroup.pageNum = 1
      setTimeout(() => {
        this.causeList = []
        this.getReasGroupList()
      }, 200)
    },
    clearCause () {
      this.pagerGroup.keyword = ""
      this.pagerGroup.pageNum = 1
      this.causeList = []
      this.getReasGroupList()
    },
    getReasGroupList () {
      const param = {
        reasGrpDesc: this.pagerGroup.keyword,
        page: this.pagerGroup.pageNum,
        size: this.pagerGroup.pageSize,
      }
      configure.getReasGroupList(param).then(res => {
        if (res.code == 200) {
          this.causeList = res.data.rows
        }
      })
    },
  }
}
</script>
<style scoped>
.itemId >>> .el-select {
  width: 100%;
}
</style>
